// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import config from "../config/config";
import func from "../config/func";
import OrderItem from "./OrderItem";
import ReadyNode from "../game/ReadyNode";
import MainGame from "../game/MainGame";
import GameTools from "../gameTool/GameTools";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Order extends cc.Component {

    n_ready: cc.Node[] = [];
    n_bottomStartPos: cc.Vec2 = cc.v2(0, 0);
    n_selectReadyNode: cc.Node = null;
    n_mainGame: MainGame = null;
    n_orderArr: any[] = [];

    destroyItem: boolean = false;
    start() {
        this.n_mainGame = this.node.parent.getComponent(MainGame);
    }
    init() {
        this.n_orderArr = this.n_mainGame.n_orderArr;
        this.creatOrder();
        this.n_selectReadyNode = null;
        config.orderArr = [];
    }
    /**
    * 生成订单
    */
    async creatOrder() {
        if (config.orderArr.length >= 4 || this.destroyItem) {
            console.log("到达订单上限");
            return;
        }
        if (this.n_ready.length == 0) {
            this.n_ready = this.n_mainGame.n_ready;
        }
        let child: cc.Node = null;
        if (config.prefabArr[config.nodeToolPath.orderItem]) {
            child = GameTools.gameTools.get(config.nodeToolPath.orderItem);
        } else {
            let prefab = await func.loadResouce(config.nodeToolPath.orderItem, cc.Prefab) as cc.Prefab;
            child = cc.instantiate(prefab);
            config.prefabArr[config.nodeToolPath.orderItem] = prefab;
        }
        if (this.n_bottomStartPos.x == 0 && this.n_bottomStartPos.y == 0) {
            this.n_bottomStartPos.x = (this.node.width - child.width * 4) / 5;
            this.n_bottomStartPos.y = this.node.height / 2;
        }
        let child_x = this.n_bottomStartPos.x + child.width / 2 + child.width * this.node.childrenCount;
        child.setPosition(cc.v2(this.node.width + child.width, this.n_bottomStartPos.y));
        let topChild = this.node.children[this.node.childrenCount - 1];
        let index = 0;
        if (topChild) {
            index = topChild.getComponent(OrderItem).n_info.index + 1;
        } else {
            index = 0;
        }
        let sub = Math.floor(Math.random() * this.n_orderArr.length),
            item = this.n_orderArr[sub],
            mixedIngredientsStr: string = item.mixedIngredients,
            mixedIngredientsArr = mixedIngredientsStr.split(","),
            orderTotal = [],
            cookingTime = 0,
            cutTime = 0;

        for (let i = 0; i < mixedIngredientsArr.length; i++) {
            let _key = parseInt(mixedIngredientsArr[i]);
            orderTotal.push(_key);
            cookingTime += config.dataJson.batching[_key].make;
            cutTime += config.dataJson.batching[_key].cutUpVegetables;
        }
        let order: OrderInfo = {
            id: parseInt(item.id),
            index: index,
            complete: false,
            finish: 0,
            total: orderTotal,
            reward: item.money,
            wrong: false,
            addFinsh: item.experience,
            cookingTime: cookingTime,
            cutTime: cutTime,
        }
        config.selectOrder = order;
        child.parent = this.node;
        child.getComponent(OrderItem).init(order);
        cc.tween(child)
            .to(1.5, { x: child_x })
            .start();
    }
    /**
     * 检查是否还有放原材料的空位置
     */
    checkReadyNode() {
        if (this.n_selectReadyNode) return true;
        for (let i = 0; i < this.n_ready.length; i++) {
            let state = this.n_ready[i].getComponent(ReadyNode).state;
            if (state == "ready") {
                this.n_selectReadyNode = this.n_ready[i];
                break;
            }
        }
        if (!this.n_selectReadyNode) {
            console.log("空位不够");
            return false;
        } else {
            return true;
        }
    }
    /**
    * 选择材料
    */
    selectMaterial(item: cc.Node, type: number) {
        if (!this.checkReadyNode()) {
            console.log("空位不够");
            return;
        } else {
            config.selectOrder.finish++;
            item.scale = 0.5;
            item.parent = this.n_selectReadyNode.children[1];
            item.setPosition(cc.v2(0, this.n_selectReadyNode.height / 4));
            let index = config.selectOrder.total.indexOf(type);
            let orderItem = this.node.children[this.node.childrenCount - 1].getComponent(OrderItem);
            if (index == -1) {
                config.selectOrder.wrong = true;
                let sub = 0;
                for (let i = 0; i < config.selectOrder.total.length; i++) {
                    let type = config.selectOrder.total[i];
                    if (type) {
                        sub = i;
                        break;
                    }
                }
                config.selectOrder.total[sub] = null;
                orderItem.changeSelectVegettables(sub, false);
            } else {
                config.selectOrder.total[index] = null;
                orderItem.changeSelectVegettables(index, true);
            }
        }
        if (config.selectOrder.finish == config.selectOrder.total.length) {
            this.n_selectReadyNode.getComponent(ReadyNode).state = "complete";
            if (config.selectOrder.wrong) {
                config.selectOrder.wrong = false;
                GameTools.gameTools.put(item, config.nodeToolPath.material);
                for (let i = 0; i < this.n_selectReadyNode.children[1].childrenCount; i++) {
                    let child = this.n_selectReadyNode.children[1].children[i];
                    GameTools.gameTools.put(child, config.nodeToolPath.material);
                    i--;
                }
                this.n_selectReadyNode.getComponent(ReadyNode).state = "ready";
                this.node.children[this.node.childrenCount - 1].getComponent(OrderItem).destroyNode();
            } else {
                config.selectOrder.complete = true;
                this.node.children[this.node.childrenCount - 1].getComponent(OrderItem).changeOrderState();
                config.orderArr.push(JSON.parse(JSON.stringify(config.selectOrder)));
                config.orderCutUpTimeArr.push(JSON.parse(JSON.stringify(config.selectOrder.cutTime)));
                this.n_mainGame.startCutUpVegetables(this.n_selectReadyNode.children[1]);
            }
            this.creatOrder();
            this.n_selectReadyNode = null;
        }
    }

    /**
     * 开始切菜
     */
    cutUpVegetables() {
        let selectReadyNode: cc.Node = null;
        for (let i = 0; i < this.n_ready.length; i++) {
            let state = this.n_ready[i].getComponent(ReadyNode).state;
            if (state == "complete") {
                selectReadyNode = this.n_ready[i].children[1];
                break;
            }
        }
        this.n_mainGame.startCutUpVegetables(selectReadyNode);
    }

    /**
     * 销毁订单时移动后面节点
     * @param order 
     */
    moveOrderNode(order: OrderInfo, destroyNode: cc.Node) {
        if (this.node.childrenCount <= 0) return;
        if(this.node.childrenCount <= 1){
            this.creatOrder();
        }
        this.destroyItem = true;
        cc.tween(destroyNode)
            .to(0.5, { opacity: 0 })
            .to(0.5, { opacity: 255 })
            .to(0.5, { opacity: 0 })
            .call(() => {
                let index = 0;
                for (let i = 0; i < this.node.childrenCount; i++) {
                    let info = this.node.children[i].getComponent(OrderItem).n_info;
                    if (info.index == order.index) {
                        index = i + 1;
                        break;
                    }
                }
                for (let i = index; i < this.node.childrenCount; i++) {
                    let child = this.node.children[i];
                    cc.tween(child)
                        .by(0.5, { x: -this.n_bottomStartPos.x - child.width })
                        .start();
                }
                destroyNode.opacity = 255;
                this.destroyItem = false;
                GameTools.gameTools.put(destroyNode, config.nodeToolPath.orderItem);

            })
            .start();
    }
    /**
     * 回收订单
     */
    recoveryOrder() {
        config.orderArr = [];
        this.n_bottomStartPos = cc.v2(0, 0);
        this.node.removeAllChildren();
    }
}
